<template>
	<view class="app-container">
		<!-- <view class="top">
			<view class="top-left">
				<image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
			</view>
			<view class="top-center">
				<text class="name">{{userInfo.username}}</text>
				<text class="reg-time">{{userInfo.reg_time}}</text>
				<view class="alert">点击头像修改个人信息</view>
			</view>
			<view class="top-right">
				<view class="score">学分<text>{{userInfo.score}}</text></view>
				<view class="level">等级<text>{{userInfo.level}}</text></view>
			</view>
		</view> -->
		
		<button :plain="true" class="avatarWx" open-type="chooseAvatar" @chooseavatar='chooseavatar'>
			<image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
		</button>
		<input id="nickName" type="nickname" class="nickName" placeholder="请输入昵称" v-model="nickName"/>	
		<button class="loginWx" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
		<button class="loginWx" @click="save">保存用户信息</button>
		
		<!-- <update-modal @close='close' v-show="showUpdateModal"></update-modal> -->
	</view>
</template>

<script>
	import updateModal from '@/components/updateModal.vue'
	const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
	import { getUserInfo, userLogin,updateUserInfo } from '@/api/index.js'
	export default {
		data() {
			return {
				avatarUrl: defaultAvatarUrl,
				nickName: '',
				showUpdateModal: false,
				userInfo: {
						id: 3,
						avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
						last_login: "2024-06-23",
						level: 1,
						mobile: "",
						openid: "ohiEf7fXD2LLbjhJFo0cUGsLOXA0",
						password: "7f67c30098016df1a464fb1fd565e9f6",
						reg_time: "2024-06-23",
						score: 5,
						sex: 0,
						token: "7f67c30098016df1a464fb1fd565e9f6",
						unionid: "",
						username: "微信用户",
						msg: "登录成功",
						status: 1
				}
		
		},
		onLoad() {
			// uni.getUserInfo({
			// 	success(res) {
			// 		console.log("res===",res)
			// 	}
			// })

		},
		methods: {
			close(isUpdate) {
				if(isUpdate) {
					//更新信息
				}
			},
			save() {
				// console.log("nickName===",this.nickName);
				console.log("avatar===",this.avatarUrl)
				
				let that = this;
				//昵称组件在input失去焦点时响应 故通过查询对象实例的方式获取
				uni.createSelectorQuery().in(this)
				    .select("#nickName")
				    .fields({
				        properties: ["value"],
				    })
				    .exec((res) => {  
				        // const nickName = res?.[0]?.value  
								that.nickName = res?.[0]?.value;
				        console.log('获取昵称', that.nickName)
								if(!that.nickName) {
									uni.showToast({
										title: '请填写昵称',
										icon: 'error'
									})
									return;
								}
								//模拟openId 用户唯一标识
								let openId = '';
								let param = {
									nickName: that.nickName,
									avatarUrl: that.avatarUrl,
									openId: openId,
								}
								updateUserInfo(param).then(res=>{
									console.log("res====",res);
									uni.showToast({
										title:"更新用户信息成功",
										icon: 'success'
									})
								})
				    })
		
			},
			chooseavatar(e) {
				let that = this
				console.log("e====",e)
				let { avatarUrl } = e.detail;
				this.avatarUrl = avatarUrl;
				
				uni.uploadFile({
					url:'https://trip.chinahood.net/api/Upfiles/pic', // 后台上传接口
					filePath: avatarUrl, // 上传图片 url
					name: 'file',
					header: {
						'Content-Type': 'multipart/form-data',
						// 'Authorization':uni.getStorageSync('token')
					},
					success(res) {
						let data = JSON.parse(res.data);
						that.avatarUrl = decodeURI(data.url);
						console.log(that.avatarUrl)
					}
				});
			},

				//获取用户信息
			getUserInfo(e) {
				console.log("登录==")
				uni.showLoading({
					mask:true,
					title: "登录中..."
				})
				let that = this;
				var p = this.getSetting();
				p.then(function(isAuth) {
				
					console.log('是否已经授权', isAuth);
					if (isAuth) {
						//eData  包括//微信头像//微信名称 还有加密的数据
						// 默认信息 不可以
						let eData = JSON.parse(e.detail.rawData);
						console.log("eData===",eData)
						console.log('e.target===',e.target)
						// that.image = eData.avatarUrl;
						
						console.log("e.target.signature===",e.target.signature)
						uni.login({
							success(res) {
								let param = {
									title: '67896789',
									code: res.code,
									encryptedData: e.target.encryptedData,
									iv: e.target.iv,
									signature: e.target.signature
								}
								
								/**调用登录接口*/
								userLogin(param).then(res=> {
									console.log("res===",res)
									// uni.showToast({
									// 	title:"获取用户信息成功",
									// 	icon:"success"
									// });
								})
								console.log("param====",param)
								// userLogin(param).then(res=>{
								// 	uni.setStorageSync(config.sessionId,res.content.session);
								// 	uni.setStorageSync(config.userInfo,JSON.stringify(res.content.user));
								// 	uni.navigateBack({
								// 	    delta: 1,
								// 	    animationType: 'pop-out',
								// 	    animationDuration: 200
								// 	});
									
								// })
							},
							fail(error) {
								// uni.showToast({
								// 	title:"获取用户信息失败",
								// 	icon:"none"
								// })
							}
						})
					} else {
						uni.showToast({
							title: '授权失败，请确认授权已开启',
							mask: true,
							icon: 'none'
						})
					}
				});
			},
			//获取用户的当前设置
			getSetting() {
				return new Promise(function(resolve, reject) {
					uni.getSetting({
						success: function(res) {
							if (res.authSetting['scope.userInfo']) {
								console.log('存在');
								console.log("res.authSetting===",res.authSetting)
								resolve(true);
							} else {
								console.log('不存在');
								resolve(false);
							}
						}
					})
				}).catch((e) => {
					console.log(e)
				});
			}
		}
	}
</script>

<style>
	.input-placeholder {
		/* color: #FFFFFF!important; */
		text-align: center;
	}
</style>

<style lang="scss" scoped>
	.app-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: calc(100vh - 100px);
		.loginWx {
			margin-top: 20rpx;
			width: 90%;
			background: #D22A24;
			color: #FFFFFF;
			font-size: 28rpx;
			height: 96rpx;
			line-height: 96rpx;
		}
	}
</style>